package com.atguigu.jdbc3;

import com.atguigu.jdbc.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*
    事务：
    转账: AA用户给BB用户转账1000

       name		balance
       AA  		1000
       BB  		3000

       ======代码=====
       try{
           SET AUTOCOMMIT = FALSE;
           对AA账户进行修改 ： update xxx set balance=1000 where name='AA'
           xxxx异常代码xxxxx
           对BB账户进行修改 ： update xxx set balance=3000 where name='BB'
           事务提交
       }catch(Exception e){
        事务回滚
       } finally{
        SET AUTOCOMMIT = true;
       }
 */
public class ThansactionDemo {

    @Test
    public void test(){
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = JDBCUtils.getConnection();
            //禁止自动提交
            connection.setAutoCommit(false);

            String sql = "update account set balance=? where name=?";
            ps = connection.prepareStatement(sql);
            //aa转出1000元
            ps.setInt(1,1000);
            ps.setString(2,"aa");
            ps.executeUpdate();

            //System.out.println(1/0);

            //bb转入1000
            ps.setInt(1,3000);
            ps.setString(2,"bb");
            ps.executeUpdate();

            connection.commit();//提交
        } catch (Exception e) {
            e.printStackTrace();
            //事务回滚
            try {
                connection.rollback();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        } finally {
            //将自动提交设置成原来的状态
            try {
                connection.setAutoCommit(true);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            JDBCUtils.close(ps,connection);
        }
    }
}













